﻿using System;
using System.Linq.Expressions;
using Hangfire;
using Hangfire.Annotations;

namespace Hello_Hangfire
{
    /// <summary>
    /// Hangfire 工具箱
    /// </summary>
    public class HangfireUtil
    {
        /// <summary>
        /// 基于队列的任务处理
        /// </summary>
        /// <param name="methodCall"></param>
        /// <returns></returns>
        public static string Enqueue(Expression<Action> methodCall)
        {
            return BackgroundJob.Enqueue(methodCall);
        }

        /// <summary>
        /// 延迟任务执行
        /// </summary>
        /// <param name="methodCall"></param>
        /// <param name="delay">时间间隔</param>
        /// <returns></returns>
        public static string Schedule(Expression<Action> methodCall, TimeSpan delay)
        {
            return BackgroundJob.Schedule(methodCall, delay);
        }

        /// <summary>
        /// 延续性任务执行（第一个任务执行后执行第二个任务）
        /// </summary>
        /// <param name="parentId">第一个job</param>
        /// <param name="methodCall"></param>
        /// <returns></returns>
        public static string ContinueWith([NotNull] string parentId, [InstantHandle][NotNull] Expression<Action> methodCall)
        {
            return BackgroundJob.ContinueWith(parentId, methodCall);
        }

        /// <summary>
        /// 定时任务执行（循环）
        /// </summary>
        /// <param name="methodCall"></param>
        /// <param name="delay">时间间隔</param>
        /// <returns></returns>
        public static void RecurringJobAddOrUpdate(Expression<Action> methodCall, Func<string> cronExpression)
        {
            RecurringJob.AddOrUpdate(methodCall, cronExpression);
        }

        /// <summary>
        /// 定时任务执行（循环）
        /// </summary>
        /// <param name="methodCall"></param>
        /// <param name="delay">时间间隔</param>
        /// <returns></returns>
        public static void RecurringJobAddOrUpdate(Expression<Action> methodCall, string cronExpression)
        {
            RecurringJob.AddOrUpdate(methodCall, cronExpression);
        }
    }
}